package alps.common.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.TextView;

import alps.common.R;


/**
 * 这是一个字体大小与控件大小自动匹配的TextView
 * 如TextView的高度为100px，则字体大小会自动设置为100px-（spacePixes*2)
 * Created by alps on 2017/2/20 0020.
 */

public class AutoAdjustTextView extends TextView {

    /**
     * 该值单位为px
     * 如果该值不为0，则需要在TextView上，下各留出指定px的空隙
     * */
    private float spacePixes = 0f;

    public AutoAdjustTextView(Context context) {
        super(context);
        setGravity(Gravity.CENTER_VERTICAL);
        setIncludeFontPadding(false);
    }


    public AutoAdjustTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setGravity(Gravity.CENTER_VERTICAL);
        setIncludeFontPadding(false);
        loadAttrs(context, attrs);
    }

    public AutoAdjustTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setGravity(Gravity.CENTER_VERTICAL);
        setIncludeFontPadding(false);
        loadAttrs(context, attrs);
    }

    private void loadAttrs(Context context, AttributeSet attrs) {
        TypedArray a = context.getResources().obtainAttributes(attrs, R.styleable.auto_adjust_textview);
        spacePixes = a.getFloat(R.styleable.auto_adjust_textview_alps_space, 0f);
        a.recycle();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = getMeasuredHeight();

        if (spacePixes > 0 && height > (spacePixes * 2)) {
            setTextSize(TypedValue.COMPLEX_UNIT_PX, height - spacePixes * 2);
        } else {
            setTextSize(TypedValue.COMPLEX_UNIT_PX, height);
        }
    }
}
